/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.UserService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.entity.IkgResponse;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.UserModel;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jeryzym
 */
@RestController
@RequestMapping("/rest/user")
public class UserController implements BaseController<UserModel> {

    private static Logger logger = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService<UserModel, String> userService;

    public UserModel format(Map<String, Object> params) {
        // TODO Auto-generated method stub
        UserModel record = new UserModel();
        record.setUser_id(IkgStringUtils.ObjectToString(params.get("user_id")));

        if (!IkgStringUtils.isNull(params.get("user_name"))) {
            record.setUser_name(IkgStringUtils.ObjectToString(params.get("user_name")));
        }
        if (!IkgStringUtils.isNull(params.get("nick_name"))) {
            record.setNick_name(IkgStringUtils.ObjectToString(params.get("nick_name")));
        }
        if (!IkgStringUtils.isNull(params.get("record_status"))) {
            record.setRecord_status(IkgStringUtils.ObjectToInt(params.get("record_status")));
        }
        /**
         * 密码变更，
         */
        if (!IkgStringUtils.isNull(params.get("user_pwd")) && !IkgStringUtils.isNull(params.get("edit_status"))
                && ((org.apache.commons.lang.StringUtils.equals(IkgStringUtils.ObjectToString(params.get("edit_status")),
                "0")
                || org.apache.commons.lang.StringUtils
                .equals(IkgStringUtils.ObjectToString(params.get("edit_status")), "2")))) {
            String salt = IkgStringUtils.randomString(6, 12);
            String encrypt = null;
            encrypt = IkgStringUtils.md5Pwd(IkgStringUtils.ObjectToString(params.get("user_pwd")), salt);
            record.setUser_pwd(encrypt);
            record.setUser_salt(salt);
            /**
             * 密码变更后生效日期变更为最新日期
             */
            record.setEffective_date(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
        }
        if (!IkgStringUtils.isNull(params.get("expire_date"))) {
            record.setExpire_date(IkgStringUtils.ObjectToString(params.get("expire_date")));
        }
        if (IkgStringUtils.isNotNull(params.get("org_id"))) {
            record.setOrg_id(IkgStringUtils.ObjectToString(params.get("org_id")));
        }

        return record;
    }

    @PostMapping("/save")
    @ApiOperation(httpMethod = "post", value = "saveOrUpdate")
//	@RequiresPermissions("mgr.user.save")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        userService.save(format(params));
        return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/delete")
    @ApiOperation(httpMethod = "post", value = "delete")
//	@RequiresPermissions("mgr.user.delete")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub

        if (!isPKeyNotNull(params) || params.get("user_name") == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        // 禁止删除当前在登录用户
        if (org.apache.commons.lang.StringUtils.equals(IkgWebUtils.getCurrentUser(),
                IkgStringUtils.ObjectToString(params.get("user_name")))) {
//            return IkgWebUtils.postMsg("系统阻止删除当前登录用户操作", IkgConstantCode.OPERFAILURE, false);
            return IkgWebUtils.postIkgResponse(false, "系统阻止删除当前登录用户操作", IkgConstantCode.OPERFAILURE);
        }
        userService.delete(params.get("user_id").toString());
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/selectOne")
//	@RequiresPermissions("mgr.user.selectone")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        UserModel record = userService.selectOne(params.get("user_id").toString());
        return IkgWebUtils.postIkgResponse(true, "查询成功!", record);
    }

    public Object selectByCond(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @param username
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/validate")
    public Object duplicateCheck(@RequestParam("userName") String username, HttpServletRequest request,
                                 HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        if (IkgStringUtils.isNull(username)) {
            result.put("valid", true);
        }
        UserModel record = userService.getUserByUsername(String.valueOf(username));
        if (IkgStringUtils.isNull(record)) {
            result.put("valid", true);
        } else {
            result.put("valid", false);
        }
        return JSONObject.fromObject(result);
    }

    public boolean isPKeyNotNull(Map<String, Object> params) {
        return params != null && params.get("user_id") != null;
    }

    /**
     * 分页列表查询
     */
    @Override
    @PostMapping("/list")
//	@RequiresPermissions("mgr.user.list")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (params == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        int pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        int pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));

        PageInfo<UserModel> users = userService.selectPage(params, pageIndex, pageSize);

        return IkgWebUtils.postResult(users.getTotal(), users.getList());
    }

    @PostMapping("/updateUserPwd")
    public Object updateUserPwd(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        UserModel record = format(params);
        userService.updateUserPwd(record.getUser_id(), record.getUser_pwd(), record.getUser_salt());
        return IkgWebUtils.postIkgResponse(true, "更新密码成功!", IkgConstantCode.OPERSUCCESS);
    }

}
